#include "head.h"
#define MAX_QUEUE_SIZE 255

int initThreadPoll(thread_poll_s *poll, int num){
    pthread_t *tids = (pthread_t*)calloc(sizeof(pthread_t),num);
    poll->tids = tids;
    poll->thread_num = num;
    for(int i=0; i<num; i++){
        pthread_t tid;
        pthread_create(&tid,NULL,threadMain,poll);
        poll->tids[i]=tid;
    }
    bzero(&poll->sessions,sizeof(Queue));
    poll->sessions.count = 0;
    poll->sessions.max_size = MAX_QUEUE_SIZE;
    poll->exit_flag = 0;
    pthread_mutex_init(&poll->lock, NULL);
    pthread_cond_init(&poll->cond, NULL);
    return 0;
}

int enQueue(int client_fd, Queue *queue){
    if(queue->count == queue->max_size){
        return -1;
    }
    Node *newnode = (Node*)calloc(sizeof(Node),1);
    ERROR_CHECK(newnode,NULL,"enqueue:node_create");

    newnode->client_fd = client_fd;
    newnode->next = NULL;

    if(queue->count == 0){
        queue->head = newnode;
        queue->tail = newnode;
        queue->count++;
        return 0;
    }

    queue->tail->next=newnode;
    queue->tail=newnode;
    queue->count++;
    return 0;
}

int deQueue(Queue *queue){
    if(queue->count == 0){
        return -1;
    }
    int client_fd = queue->head->client_fd;
    Node *head_node = queue->head;
    queue->head =queue->head->next;
    free(head_node);
    queue->count--;
    return client_fd;
}
